package Utils
{
	import Game.Bullet;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	
	import mx.controls.Image;
	import mx.core.UIComponent;
	
	import spark.components.BorderContainer;
	import spark.components.Group;

	public class CollisionDetection
	{
		static public function checkForCollision(world:UIComponent, item:UIComponent, useParentPosition:Boolean, clipRect:Rectangle, p_alphaTolerance:Number = 0 ):Rectangle {

			// set up the image to use:
			var img:BitmapData = new BitmapData(clipRect.width, clipRect.height, false);
			
			// draw in the world:
			var mat:Matrix = world.transform.concatenatedMatrix;
			mat.tx = -world.x-clipRect.x;
			mat.ty = -world.y-clipRect.y;
			img.draw(world, mat, new ColorTransform(1,1,1,1,255,-255,-255,p_alphaTolerance));

			// overlay the item:
			mat = item.transform.concatenatedMatrix;
			
			if(useParentPosition)
			{
				mat.tx = -world.x-clipRect.x+item.parent.x;
				mat.ty = -world.y-clipRect.y+item.parent.y;
			}
			else
			{
				mat.tx = -world.x-clipRect.x+item.x;
				mat.ty = -world.y-clipRect.y+item.y;
			}
			
			img.draw(item,mat, new ColorTransform(1,1,1,1,255,255,255,p_alphaTolerance),"difference");

			// find the intersection:
			var intersection:Rectangle = img.getColorBoundsRect(0xFFFFFFFF,0xFF00FFFF);

			// if there is no intersection, return null:
			if (intersection.width == 0) { 
				return null; 
			}
			
					var imm:Image = new Image();
					imm.source = new Bitmap(img);
					
					var bc:BorderContainer = world as BorderContainer;
					bc.addElement(imm);
			
			return intersection;
		}

	}
}